package edu.lhh;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class codeServlet
 */
@WebServlet("/code")
public class codeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public codeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		String str = this.makeCode(4);
		session.setAttribute("code",str);
		BufferedImage img = new BufferedImage(80,25,BufferedImage.TYPE_INT_RGB);
		Graphics g = img.getGraphics();
		g.setColor(Color.white);
		g.fillRect(0, 0, 80, 25);
		g.setColor(Color.black);
		g.setFont(new Font("宋体",Font.BOLD,20));
		g.drawString(str, 5, 20);
		g.dispose();
		
		ServletOutputStream sos = response.getOutputStream();
		ImageIO.write(img,"jpeg",sos);
		sos.flush();
		sos.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	public String makeCode(int size){
		String str="123456789abcdefghijklmnopqrlstuvwxyz";
		Random rdm = new Random();
		StringBuffer buf = new StringBuffer();
		for(int i=0;i<size;i++){
			int leng = str.length();
			int pos = rdm.nextInt(leng);
			buf.append(str.substring(pos, pos+1));
			
		}
		return buf.toString();
	}

}
